package com.ithao.controller;

import com.ithao.common.GlobalConst;
import com.ithao.common.QuestionConst;
import com.ithao.entity.PageResult;
import com.ithao.entity.QueryPageBean;
import com.ithao.entity.Result;
import com.ithao.pojo.Question;
import com.ithao.pojo.QuestionItem;
import com.ithao.pojo.User;
import com.ithao.service.QuestionService;
import com.ithao.utils.JedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author : ZhangHao
 * @version :1.0
 * @date :Created in 2020/2/3
 * @description : 题目控制器
 */
@RestController
@Slf4j
@RequestMapping("/question")
public class QuestionController {
    @Autowired
    private QuestionService questionService;

    /**
     * 分页获取题目列表
     *
     * @param queryPageBean
     * @return
     */
    @PostMapping("/findListByPage")
    public Result questionList(@RequestBody QueryPageBean queryPageBean) {
        if (queryPageBean == null) {
            queryPageBean = new QueryPageBean();
            queryPageBean.setCurrentPage(1);
            queryPageBean.setPageSize(10);
        }
        log.info("questionList分页查询 queryPageBean:{}", queryPageBean);
        PageResult pageResult = questionService.findByPage(queryPageBean);
        return new Result(true, "获取题目列表成功", pageResult);
    }

    /**
     * 添加基础题目
     *
     * @param request
     * @param
     */
    @PostMapping("addOrUpdate")
    public Result addOrUpdate(HttpServletRequest request, @RequestBody Question question) {
        // 获取表单数据
        try {
            User user = (User) request.getSession().getAttribute(GlobalConst.SESSION_KEY_USER);
            // 从上下文获取用户ID，调试默认为1
            question.setUserId(user != null ? user.getId() : 1);
            // 保存数据
            questionService.addOrUpdate(question);
            // 处理图片
            processImage(question);
            return new Result(true, "更新成功");
        } catch (RuntimeException e) {
            log.error("addOrUpdate", e);
            return new Result(false, e.getMessage());
        }
    }

    @PreAuthorize("hasAuthority('QUESTION_DELETE')")
    @PostMapping("/delete")
    public Result delete(@RequestParam("id") Integer id) {
        log.info("[删除试题] id : {}", id);
        questionService.delete(id);
        return new Result(true, "删除成功");
    }

    /**
     * 分页获取精选列表
     */
    @RequestMapping("findClassicListByPage")
    public Result questionClassicList(@RequestBody QueryPageBean queryPageBean) {
        if (queryPageBean == null) {
            queryPageBean = new QueryPageBean();
            queryPageBean.setCurrentPage(1);
            queryPageBean.setPageSize(10);
        }
        log.info("questionList:精选题目 queryPageBean:{}", queryPageBean);
        PageResult pageResult = questionService.findClassicByPage(queryPageBean);
        return new Result(true, "获取经典题目列表成功", pageResult);
    }

    /**
     * 更新题目为经典题目
     */
    @RequestMapping("updateClassic")
    public Result updateClassic(Integer questionId) {
        try {
            log.info("updateClassic更新题目为经典题目 questionId:{}", questionId);
            questionService.updateIsClassic(questionId, QuestionConst.ClassicStatus.CLASSIC_STATUS_YES.ordinal());
            return new Result(true, "更新成功");
        } catch (RuntimeException e) {
            log.error("updateClassic", e);
            return new Result(false, "更新失败");
        }
    }

    /**
     * 题目预览
     */
    @RequestMapping("/findById")
    public Result findById(Integer questionId) {
        try {
            Question question = questionService.findQuestionById(questionId);
            return new Result(true, "获取成功", question);
        } catch (RuntimeException e) {
            log.error("findById", e);
            return new Result(false, "获取失败," + e.getMessage());
        }
    }

    /**
     * 题目下架
     */
    @PostMapping("/down")
    public Result down(@RequestParam("id") Integer id) {
        log.info("[下架] :requestionId : {}", id);
        Question question = questionService.findQuestionById(id);
        if (question.getStatus() == 2) {
            return new Result(false, "该题已是下架状态");
        }
        questionService.down(id);
        return new Result(true, "下架成功");
    }

    // 处理图片存储
    private void processImage(Question question) {
        List<QuestionItem> questionItemList = question.getQuestionItemList();
        if (questionItemList == null && questionItemList.size() == 0) {
            return;
        }
        Integer userId = question.getUserId();
        // 说明有选项
        for (QuestionItem questionItem : questionItemList) {
            if (questionItem.getImgUrl() != null && questionItem.getImgUrl().length() > 0) {
                // 删除redis set中的图片路径信息
                if (JedisUtils.isUsed()) {
                    JedisUtils.getResource().srem(GlobalConst.REDIS_KEY_SET_UPLOAD_IMAGE.concat(userId + ""), questionItem.getImgUrl());
                    log.info("redis delele value:{}", questionItem.getImgUrl());
                }
            }
        }
    }
}
